package com.ccsu.mymarket.controller;

import com.ccsu.mymarket.entity.User;
import com.ccsu.mymarket.entity.message.Meta;
import com.ccsu.mymarket.entity.message.Result;
import com.ccsu.mymarket.exception.MyException;
import com.ccsu.mymarket.jwt.JWTUtils;
import com.ccsu.mymarket.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {
    private final UserService userService;

    public LoginController(@Autowired UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
//    登录，按照 User类 格式传入登录信息
    public Result login(@RequestBody User user) throws MyException {
        if(user==null)
            throw new MyException("登录信息为空！");
        User userInfo=userService.checkLoginInfo(user);
        if (userInfo!=null){
            Map data=new HashMap();
            data.put("user",userInfo);
            data.put("token", JWTUtils.buildJWT(userInfo.getId()));
            return new Result(new Meta(200, "登录成功！"), data);
        }
        else {
            throw new MyException(500,"登录时发生未知错误");
        }
    }

    @PostMapping("/register")
//    注册,按User实体类传入用户基本信息，若为商家角色则需额外传入店铺的基本信息
    public Result registerIn(@RequestBody Map data) throws Exception {
        if(data==null)
            throw new MyException("注册信息为空！");
        else {
                if (userService.registerIn(data))
                    return new Result(new Meta(200,"注册成功，请登录！"),null);
            throw new MyException(500,"注册时发生未知错误");
        }
    }

    @GetMapping("/logout")
    public Result logout(@RequestHeader("token") String token){
        if (token == null)
            return new Result(new Meta(200, "成功注销登录！"), null);
        return new Result(new Meta(500, "注销失败，token不为空！"), null);
    }

}

